# memento/views.py
from memento.models import UserStateMemento
from algorithm.models import UserTagMastery, UserProblemRecommendation, UserComprehensiveLevel
from problems.serializers import ProblemSerializer
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes, permission_classes
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth.models import User
import io
import sys
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework_simplejwt.authentication import JWTAuthentication

from utils.logging_utils import log_request_response


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def create_user_memento(request):
    user_id = request.user.id
    try:
        memento = UserStateMemento.create_memento(user_id)
        return JsonResponse({
            'message': 'Memento created successfully.',
            'memento_id': memento.pk
        }, status=200)
    except User.DoesNotExist:
        return JsonResponse({'error': 'User not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def restore_user_memento(request):
    user_id = request.user.id
    try:
        UserStateMemento.restore_memento(user_id)
        return JsonResponse({
            'message': 'User state restored successfully.'
        }, status=200)
    except User.DoesNotExist:
        return JsonResponse({'error': 'User not found'}, status=404)
    except UserStateMemento.DoesNotExist:
        return JsonResponse({'error': 'Memento not found for user'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
